package reposit

import (
	"errors"
	"fmt"
	"github.com/jinzhu/gorm"
	"sbd_zgqx/inits"
	"sbd_zgqx/models"
)

type WeatherReposit struct {
	Db inits.Database
}

func (repo *WeatherReposit) ListArea() (isProvince []models.Province, err error) {
	db := repo.Db.DB
	err = db.Raw("select * from province where cid !=0").Scan(&isProvince).Error
	if err != nil {
		return
	}
	return isProvince, nil
}

func (repo *WeatherReposit) InsertWeather(weather models.Weather) (bool, error) {
	db := repo.Db.DB
	err := db.Table("weather").Create(weather).Error
	if err != nil {
		return false, errors.New(fmt.Sprintf("insert weather err:%s", err))
	}
	return true, err
}

func (repo *WeatherReposit) IsLoadWeather(weather models.Weather) (bool, error) {
	db := repo.Db.DB
	isWeather := &models.Weather{}
	if !errors.Is(db.Raw("select * from weather where serial=? and lastUpdate=?", weather.Serial, weather.LastUpdate).Scan(&isWeather).Error, gorm.ErrRecordNotFound) {
		return false, errors.New("日期已存在！")
	}
	return true, nil
}
